import vtk
import pygst
pygst.require("0.10")
import gst

class RealCamera():
    def __init__(self):
        
        self.videosource = "device=/dev/video0"
        self.width = 640
        self.height= 480
        
        self.configuration =   "v4l2src " + self.videosource + " ! \
                                video/x-raw-rgb,width="+str(self.width)+",height="+str(self.height)+" ! \
                                videorate ! \
                                video/x-raw-rgb,framerate=25/2 ! \
                                videoscale ! \
                                video/x-raw-rgb,width="+str(self.width)+",height="+str(self.height)+" ! \
                                ffmpegcolorspace ! identity name=artoolkit ! appsink name=sink"
                                
        self.player = gst.parse_launch(self.configuration)
        self.sink   = self.player.get_by_name("sink")
        
        self.initVTK()
        self.dummyFillBuffer()
        
    def dummyFillBuffer(self):
        buffer = ""
        for i in range( self.width * self.height * 3):
            buffer += " "
        
        self.impCamera.CopyImportVoidPointer(buffer, len(buffer))
        
    def initVTK(self):
        self.impCamera = vtk.vtkImageImport()
        self.impCamera.SetDataScalarTypeToUnsignedChar()
        self.impCamera.SetNumberOfScalarComponents(3)
        self.impCamera.SetDataExtent(0,self.width-1,0,self.height-1,0,0)
        self.impCamera.SetWholeExtent(0,self.width-1,0,self.height-1,0,0)
        self.actCamera = vtk.vtkImageActor()
        self.actCamera.SetInput(self.impCamera.GetOutput())
        
        upside_down = vtk.vtkTransform()
        upside_down.RotateX(180)
        self.actCamera.SetUserTransform(upside_down)
        
    def GetActor(self):
        return self.actCamera
        
    def startCapturing(self):
        self.player.set_state(gst.STATE_PLAYING)
        
    def stopCapturing(self):
        self.player.set_state(gst.STATE_NULL)
        
    def Update(self):
        self.videoBuffer = self.sink.emit("pull-buffer")
        self.impCamera.CopyImportVoidPointer(self.videoBuffer.data, len(self.videoBuffer.data))
        
    def GetVideoBuffer(self):
        return self.videoBuffer